/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.perficient.ibuzz.controller;

import com.google.api.client.googleapis.GoogleHeaders;
import com.google.api.client.googleapis.GoogleTransport;
import com.google.api.client.googleapis.json.JsonCParser;
import com.google.api.client.http.HttpTransport;
import com.perficient.ibuzz.service.Auth;
import com.perficient.ibuzz.model.Message;
import com.perficient.ibuzz.model.MessageReceiver;
import com.perficient.ibuzz.model.MessageSender;
import com.perficient.ibuzz.service.BuzzMessageReceiver;
import com.perficient.ibuzz.service.BuzzMessageSender;
import com.perficient.ibuzz.ui.FormMessageSender;
import java.util.Date;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author Trainning
 */
public class IBuzzController {

    private HttpTransport transport = null;

    public IBuzzController() {
        login();
    }

    public void initializeApp() {
        new FormMessageSender(this).setVisible(true);
    }

    private static HttpTransport setUpTransport() {
        HttpTransport transport = GoogleTransport.create();
        GoogleHeaders headers = (GoogleHeaders) transport.defaultHeaders;
        headers.setApplicationName("Google-BuzzSample/1.0");
        transport.addParser(new JsonCParser());
        return transport;
    }

    private void login() {
        try {
            transport = setUpTransport();
            Auth.authorize(transport);
        } catch (Exception ex) {
            Logger.getLogger(IBuzzController.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    public void postMessage(Message message) {
        MessageSender messageSender = new BuzzMessageSender(transport);
        messageSender.sendMessage(message);
    }

    public List<Message> retrieveMessages() {
        MessageReceiver msgReceiver = new BuzzMessageReceiver(transport);
        return msgReceiver.getMessages();
    }

    public boolean isOutOfDate(Date lastupdate) {
        MessageReceiver receiver = new BuzzMessageReceiver(transport);
        return receiver.isOutOfDate(lastupdate);
    }
}
